<template>
  <div>
    <el-card class="location-card" shadow="hover">
      <el-tabs
        v-model="activeTab"
        type="card"
        @tab-click="handleTabClick"
      >
        <el-tab-pane label="党建地点" name="location">
          <MainLocation :locations="locations" :searchTerm="searchTerm" />
        </el-tab-pane>
        <el-tab-pane label="我的预约" name="reservations">
          <MyReservations />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { LocationListService } from '@/api/location.js';
import MainLocation from '@/components/Location/MainLocation.vue';
import MyReservations from '@/components/Location/MyReservations.vue';

// 状态管理
const locations = ref([]); // 存储地点信息
const searchTerm = ref(''); // 用于存储传递的地点名称
const activeTab = ref('location'); // 当前选中的标签

const route = useRoute(); // 获取路由信息

const handleTabClick = (tab) => {
  // 点击标签后的逻辑
  console.log(`Tab clicked: ${tab.props.label}`);
};

// 获取地点数据并在控制台输出
const getLocationData = async () => {
  try {
    const response = await LocationListService({ page: 1, size: 10 }); // 获取前10个地点
    // 处理后端返回的数据
    locations.value = response.data.list.map(item => ({
      id: item.id,
      name: item.name,
      photo: item.photo,
      number: item.number,
      balance: item.balance,
      content: item.content,
      address: item.address, // 确保这个字段存在
      type: item.type // 确保这个字段存在
    })) || [];
    console.log('Fetched locations:', locations.value); // 输出获取到的数据

    // 根据路由传递的参数设置搜索条件
    if (route.params.locationId) {
      const locationId = route.params.locationId;
      const foundLocation = locations.value.find(loc => loc.id === locationId);
      if (foundLocation) {
        searchTerm.value = foundLocation.name; // 如果找到了，根据 ID 设置搜索名称
      }
    } else if (route.params.locationName) {
      searchTerm.value = route.params.locationName; // 如果传递的是地点名称
    }
  } catch (error) {
    console.error('Failed to fetch locations:', error);
  }
};

// 组件挂载时获取数据
onMounted(() => {
  getLocationData();
});
</script>

<style scoped>
.location-card {
  width: 70%; /* 卡片宽度占70% */
  margin: 0 auto; /* 居中显示 */
  border-radius: 10px; /* 圆角 */
}

/* 你可以在这里添加更多的样式来美化页面 */
</style>
